class GuanliManager {
    constructor() {
        this.guanliURL = 'https://sxhyl-1306101765.cos.ap-beijing.myqcloud.com/guanli.csv';
        this.guanliData = null;

        this.defualtData = [
        // 0: 关键指标数据
       `女性职工总数,517
        在孕人数,18
        哺乳期人数,29
        孕晚期在岗,6`,
        
        // 1: 部门婚育状态数据 (CSV格式)
       `综合管理部,5,2,0,5
        协作一部,2,2,0,10
        协作二部,5,1,0,2
        协作三部,97,45,6,56
        协作四部,152,75,12,87`,
        
        // 2: 月份新增孕妇数据
       `10,1
        11,1
        12,2
        1,0
        2,1
        3,2
        4,2
        5,2
        6,1
        7,1
        8,2
        9,3`,
        
        // 3: 部门预产期数据 (保持原结构)
       `机械工程室,2025-10,0,2025-11,1,2025-12,0,2026-01,0,2026-02,0,2026-03,0
        传动工程室,2025-10,0,2025-11,0,2025-12,0,2026-01,0,2026-02,0,2026-03,0
        材料工程室,2025-10,0,2025-11,0,2025-12,0,2026-01,0,2026-02,0,2026-03,0,
        新能源工程室,2025-10,0,2025-11,0,2025-12,0,2026-01,1,2026-02,0,2026-03,1
        人工智能工程室,2025-10,0,2025-11,1,2025-12,0,2026-01,1,2026-02,1,2026-03,0
        计算机系统室,2025-10,0,2025-11,0,2025-12,1,2026-01,0,2026-02,0,2026-03,0
        智慧能源室,2025-10,1,2025-11,0,2025-12,0,2026-01,0,2026-02,0,2026-03,0
        通信工程室,2025-10,0,2025-11,0,2025-12,0,2026-01,0,2026-02,0,2026-03,0
        图像技术室,2025-10,0,2025-11,0,2025-12,0,2026-01,0,2026-02,0,2026-03,0
        光学工程室,2025-10,0,2025-11,0,2025-12,0,2026-01,0,2026-02,0,2026-03,0
        医学工程室,2025-10,0,2025-11,0,2025-12,1,2026-01,0,2026-02,0,2026-03,0
        计量工程室,2025-10,0,2025-11,0,2025-12,0,2026-01,0,2026-02,0,2026-03,1`,
        
        // 4: 案源分配数据
       `待审案件池,1240
        本领域,900
        相关领域,300
        跨单元,140`];

        this.refresh()
    }


    // 刷新数据
    refresh() {
        this.loadData();
    }

    // url 增加时间戳
    urlAddTimestamp(url){
        /* 添加时间戳参数强制更新 */
        const timestamp = new Date().getTime();
        return `${url}?t=${timestamp}`; // 添加唯一时间戳参数
    }

    // 新增：加载数据并更新页面
    async loadData() {
        let csvText = '';
        try {
            const res = await fetch(this.urlAddTimestamp(this.guanliURL));
            if (!res.ok) throw new Error('网络错误');
            csvText = await res.text();
        } catch (e) {
            // 加载失败，使用默认数据
            this.updateUIWithDefault();
            return;
        }
        this.parseAndUpdate(csvText);
    }

    // 解析CSV并更新页面
    parseAndUpdate(csvText) {
        console.log('加载管理数据：', csvText.slice(0,200)+'...');
        const lines = csvText.split(/\r?\n/).map(l => l.trim()).filter(l => l);
        // 关键指标
        let stats = {};
        for (let i = 0; i < 4; i++) {
            const [k, v] = lines[i].split(',');
            stats[k] = v;
        }
        this.updateStatsCard(stats);

        // 部门婚育状态
        let deptStart = lines.findIndex(l => l.startsWith('部门')) + 1;
        let deptEnd = deptStart;
        while (deptEnd < lines.length && lines[deptEnd] && !lines[deptEnd].startsWith('月份')) deptEnd++;
        const deptData = lines.slice(deptStart, deptEnd);
        this.updateMarriageCharts(deptData);

        // 月份新增孕妇
        let monthStart = lines.findIndex(l => l.startsWith('月份')) + 1;
        let monthEnd = monthStart;
        // 修正：如果后面没有"部门"，直接取到末尾
        while (monthEnd < lines.length && lines[monthEnd] && !lines[monthEnd].startsWith('部门')) monthEnd++;
        const monthData = lines.slice(monthStart, monthEnd);
        this.updateTrendChart(monthData);

        // 预产期分布
        let birthStart = lines.findIndex(l => l.startsWith('部门,时间')) + 1;
        let birthEnd = birthStart;
        while (birthEnd < lines.length && lines[birthEnd] && !lines[birthEnd].startsWith('待审案件池')) birthEnd++;
        const birthData = lines.slice(birthStart, birthEnd);
        this.updateGanttChart(birthData);

        // 案源分配
        // 案源分配
        let caseStart = lines.findIndex(l => l && l.startsWith('待审案件池'));
        // 直接取到文件末尾或下一个空行
        let caseEnd = caseStart;
        while (caseEnd < lines.length && lines[caseEnd] && lines[caseEnd].includes(',')) caseEnd++;
        const caseData = caseStart >= 0 ? lines.slice(caseStart, caseEnd) : [];
        this.updateCasePool(caseData);
    }

    // 更新关键指标卡片
    updateStatsCard(stats) {
        const grid = document.getElementById('statGrid');
        if (!grid) return;
        const items = grid.querySelectorAll('.stat-item .stat-number');
        items[0].textContent = stats['女性职工总数'] || '-';
        items[1].textContent = stats['在孕人数'] || '-';
        items[2].textContent = stats['哺乳期人数'] || '-';
        items[3].textContent = stats['孕晚期在岗'] || '-';
    }

    // 更新婚育分布图（饼图/柱状图）
    updateMarriageCharts(deptData) {
        // 统计总数
        let total = {未婚:0,已婚未育:0,在孕:0,已育:0};
        let deptArr = [];
        deptData.forEach(row => {
            const arr = row.split(',');
            deptArr.push({
                name: arr[0],
                未婚: Number(arr[1]),
                已婚未育: Number(arr[2]),
                在孕: Number(arr[3]),
                已育: Number(arr[4])
            });
            total['未婚'] += Number(arr[1]);
            total['已婚未育'] += Number(arr[2]);
            total['在孕'] += Number(arr[3]);
            total['已育'] += Number(arr[4]);
        });

        // ---- 婚育状态分布饼图 ----
        const marriageContainer = document.getElementById('marriageStatusChart');
        if (marriageContainer) {
            const sum = Object.values(total).reduce((a, b) => a + b, 0);
            const percent = Object.keys(total).map(k => sum ? Math.round(total[k] / sum * 100) : 0);
            const circleTotal = 2 * Math.PI * 80; // r=80
            const colors = ['#ff9a9e', '#fad0c4', '#a18cd1', '#fbc2eb'];

            // 计算每个扇形的dasharray和dashoffset
            let dashArray = [];
            let dashOffset = [];
            let acc = 0;
            Object.keys(total).forEach((k, i) => {
                const value = total[k];
                const p = sum ? value / sum : 0;
                const len = p * circleTotal;
                dashArray.push(`${len} ${circleTotal - len}`);
                dashOffset.push(-acc);
                acc += len;
            });

            marriageContainer.innerHTML = `
                <div class="chart-title">女性职工婚育状态分布</div>
                <div class="chart">
                  <div class="pie-chart">
                    <svg viewBox="0 0 200 200" width="200" height="200">
                      ${Object.keys(total).map((k, i) => `
                        <circle cx="100" cy="100" r="80" fill="none" stroke="${colors[i]}" stroke-width="40"
                          stroke-dasharray="${dashArray[i]}"
                          stroke-dashoffset="${dashOffset[i]}"
                          transform="rotate(-90 100 100)"/>
                      `).join('')}
                    </svg>
                  </div>
                </div>
                <div class="legend">
                  ${Object.keys(total).map((k, i) => `
                    <div class="legend-item">
                      <div class="legend-color" style="background: ${colors[i]};"></div>
                      <span>${k} (${percent[i]}%)</span>
                    </div>
                  `).join('')}
                </div>
            `;
        }

        // ---- 各部门婚育状态分布堆叠柱状图 ----
        const deptContainer = document.getElementById('deptMarriageTable');
        if (deptContainer) {
            // 让柱状图在父容器宽度内自适应，每个柱子等分空间
            const deptCount = deptArr.length;
            deptContainer.innerHTML = `
                <div class="chart-title">各部门婚育状态分布</div>
                <div class="chart">
                  <div class="bar-chart" style="
                        display: flex;
                        gap: 8px;
                        justify-content: space-between;
                        align-items: flex-end;
                        width: 100%;
                        box-sizing: border-box;
                        ">
                    ${deptArr.map(d => {
                        const sum = d.未婚 + d.已婚未育 + d.在孕 + d.已育;

                        // const percentUnmarried = sum ? (d.未婚 / sum * 100).toFixed(1) : 0;
                        // const percentMarriedNoChild = sum ? (d.已婚未育 / sum * 100).toFixed(1) : 0;
                        // const percentPregnant = sum ? (d.在孕 / sum * 100).toFixed(1) : 0;
                        // const percentHasChild = sum ? (d.已育 / sum * 100).toFixed(1) : 0;
                        // // 打印每根柱子的占比
                        // console.log(
                        //     `${d.name}：未婚${percentUnmarried}% 已婚未育${percentMarriedNoChild}% 在孕${percentPregnant}% 已育${percentHasChild}%`
                        // );

                        // 每个柱子宽度自适应，最小24px，最大48px
                        return `
                          <div class="bar-group" style="
                                flex: 1 1 0;
                                min-width: 24px;
                                max-width: 48px;
                                display: flex;
                                flex-direction: column;
                                align-items: center;
                                ">
                            <div class="bar-stack" style="
                                    height: 120px;
                                    width: 100%;
                                    min-width: 16px;
                                    max-width: 48px;
                                    display: flex;
                                    flex-direction: column-reverse;
                                    border-radius: 8px;
                                    overflow: hidden;
                                    box-shadow: 0 2px 8px rgba(0,0,0,0.04);
                                    ">
                              <div class="bar-segment" style="height:${sum ? d.未婚/sum*100 : 0}%; background:#ff9a9e;"></div>
                              <div class="bar-segment" style="height:${sum ? d.已婚未育/sum*100 : 0}%; background:#fad0c4;"></div>
                              <div class="bar-segment" style="height:${sum ? d.在孕/sum*100 : 0}%; background:#a18cd1;"></div>
                              <div class="bar-segment" style="height:${sum ? d.已育/sum*100 : 0}%; background:#fbc2eb;"></div>
                            </div>
                            <div class="bar-label" style="margin-top:6px;font-size:11px;text-align:center;word-break:break-all;">${d.name}</div>
                          </div>
                        `;
                    }).join('')}
                  </div>
                </div>
                <div class="legend" style="margin-top:8px;">
                  <div class="legend-item">
                    <div class="legend-color" style="background: #ff9a9e;"></div>
                    <span>未婚</span>
                  </div>
                  <div class="legend-item">
                    <div class="legend-color" style="background: #fad0c4;"></div>
                    <span>已婚未育</span>
                  </div>
                  <div class="legend-item">
                    <div class="legend-color" style="background: #a18cd1;"></div>
                    <span>在孕</span>
                  </div>
                  <div class="legend-item">
                    <div class="legend-color" style="background: #fbc2eb;"></div>
                    <span>已育</span>
                  </div>
                </div>
            `;
        }
    }

    // 更新趋势折线图
    updateTrendChart(monthData) {
        const trendContainer = document.getElementById('trendChart');
        if (!trendContainer) return;

        // 解析数据
        const months = [];
        const values = [];
        monthData.forEach(row => {
            const arr = row.split(',');
            if (arr.length === 2) {
                months.push(arr[0]);
                const num = Number(arr[1]);
                values.push(isNaN(num) ? 0 : num); // 防止NaN
            }
        });

        // 原始样式参数
        const chartWidth = 400;
        const chartHeight = 200;
        const leftPadding = 40;
        const rightPadding = 40;
        const bottomPadding = 20;
        const topPadding = 20;
        const pointCount = months.length;
        const xStep = (chartWidth - leftPadding - rightPadding) / (pointCount > 1 ? pointCount - 1 : 1);

        // Y轴最大值
        const maxValue = Math.max(...values, 5);
        const minValue = 0;

        // 生成折线点
        const points = values.map((v, i) => {
            const x = leftPadding + i * xStep;
            const y = chartHeight - bottomPadding - ((v - minValue) / (maxValue - minValue) * (chartHeight - topPadding - bottomPadding));
            return `${x},${y}`;
        }).join(' ');

        // 生成数据点
        const circles = values.map((v, i) => {
            const x = leftPadding + i * xStep;
            const y = chartHeight - bottomPadding - ((v - minValue) / (maxValue - minValue) * (chartHeight - topPadding - bottomPadding));
            return `<circle cx="${x}" cy="${y}" r="4" fill="#ff9a9e"/>`;
        }).join('');

        // X轴标签
        const xLabels = months.map((m, i) => {
            const x = leftPadding + i * xStep;
            return `<text x="${x}" y="${chartHeight - 5}" font-size="10" fill="#8a6d7c" text-anchor="middle">${m}月</text>`;
        }).join('');

        // // Y轴标签（5个刻度）
        // const yTicks = 5;
        // const yLabels = Array.from({length: yTicks}, (_, i) => {
        //     const v = minValue + Math.round((maxValue - minValue) * (yTicks - 1 - i) / (yTicks - 1));
        //     const y = chartHeight - bottomPadding - ((v - minValue) / (maxValue - minValue) * (chartHeight - topPadding - bottomPadding));
        //     return `<text x="${leftPadding - 15}" y="${y + 4}" font-size="10" fill="#8a6d7c" text-anchor="end">${v}</text>`;
        // }).join('');

        // 生成Y轴标签（整数分布，适合小范围数据）
        const yLabels = [];
        for (let v = minValue; v <= maxValue; v++) {
            const y = chartHeight - bottomPadding - ((v - minValue) / (maxValue - minValue || 1) * (chartHeight - topPadding - bottomPadding));
            yLabels.push(`<text x="${leftPadding - 15}" y="${y + 4}" font-size="10" fill="#8a6d7c" text-anchor="end">${v}</text>`);
        }

        // 网格线
        const gridLines = `
            <line x1="${leftPadding}" y1="${topPadding}" x2="${leftPadding}" y2="${chartHeight - bottomPadding}" stroke="#e0e0e0" stroke-width="1"/>
            <line x1="${leftPadding}" y1="${chartHeight - bottomPadding}" x2="${chartWidth - rightPadding}" y2="${chartHeight - bottomPadding}" stroke="#e0e0e0" stroke-width="1"/>
        `;

        trendContainer.innerHTML = `
            <div class="chart-title">新增孕妇数量（过去12个月）</div>
            <div class="chart">
                <div class="line-chart">
                    <svg viewBox="0 0 ${chartWidth} ${chartHeight}" width="100%" height="100%">
                        ${gridLines}
                        <polyline points="${points}" fill="none" stroke="#ff9a9e" stroke-width="3"/>
                        ${circles}
                        ${xLabels}
                        ${yLabels.join('')}
                    </svg>
                </div>
            </div>
        `;
    }

    // 更新预产期分布图（甘特图）
     updateGanttChart(birthData) {
        const ganttContainer = document.querySelector('.gantt-chart');
        if (!ganttContainer) return;

        // 解析所有月份
        let allMonths = [];
        birthData.forEach(row => {
            const arr = row.split(',');
            for (let i = 1; i < arr.length; i += 2) {
                if (!allMonths.includes(arr[i])) {
                    allMonths.push(arr[i]);
                }
            }
        });
        // 按时间升序排序
        allMonths.sort((a, b) => a.localeCompare(b));
        allMonths = allMonths.filter(m => m && m.includes('-'));

        // 生成每个部门的甘特条
        ganttContainer.innerHTML = birthData.map(row => {
            const arr = row.split(',');
            const dept = arr[0];
            // 构建每个月的数量
            let monthMap = {};
            for (let i = 1; i < arr.length; i += 2) {
                monthMap[arr[i]] = Number(arr[i + 1]);
            }
            // 生成条
            const bars = allMonths.map((month, idx) => {
                const val = monthMap[month] || 0;
                // left和width都严格等分，保证第一个月左侧对齐
                const left = (idx / allMonths.length) * 100;
                const width = (1 / allMonths.length) * 100;
                return val > 0
                    ? `<div class="gantt-bar" style="position:absolute;left:${left}%;width:${width}%;height:100%;text-align:center;line-height:24px;">${val}</div>`
                    : `<div style="position:absolute;left:${left}%;width:${width}%;height:100%;"></div>`;
            }).join('');
            return `
                <div class="gantt-row" style="display:flex;align-items:center;margin-bottom:6px;">
                    <div class="gantt-label" style="width:80px;text-align:right;padding-right:8px;font-size:clamp(10px, 2vw, 15px);">${dept}</div>
                    <div class="gantt-timeline" style="position:relative;flex:1;height:24px;">
                        ${bars}
                    </div>
                </div>
            `;
        }).join('');

        // 更新底部月份标签，保证每个标签宽度与条宽度一致且对齐
        const infoText = ganttContainer.parentElement.nextElementSibling;
        if (infoText) {
            infoText.innerHTML = `
                <div style="display: flex; margin-top: 10px;margin-left: 80px;">
                    <div style="position:relative;flex:1;">
                    ${allMonths.map((m, idx) => {
                        const width = (1 / allMonths.length) * 100;
                        return `<span style="
                            display:inline-block;
                            width:${width}%;
                            text-align:center;
                            font-size:clamp(9px, 2vw, 15px);
                            color:#8a6d7c;
                        ">${Number(m.split('-')[1])}月</span>`;
                    }).join('')}
                    </div>
                </div>
            `;
        }
    }

    // 更新案源分配数据
    updateCasePool(caseData) {
        // caseData: ["待审案件池,1240", "本领域,900", "相关领域,300", "跨单元,140"]
        const casePoolPage = document.getElementById('casePoolPage');
        if (!casePoolPage) return;
        const statGrid = casePoolPage.querySelector('.stat-grid');
        if (!statGrid) return;

        // 解析数据
        let pool = {
            "待审案件池": "-",
            "本领域": "-",
            "相关领域": "-",
            "跨单元": "-"
        };
        caseData.forEach(row => {
            const arr = row.split(',');
            if (arr.length === 2) {
                pool[arr[0].trim()] = arr[1].trim();
            }
        });

        // 更新页面
        const items = statGrid.querySelectorAll('.stat-item .stat-number');
        if (items.length >= 4) {
            items[0].textContent = pool["待审案件池"] || '-';
            items[1].textContent = pool["本领域"] || '-';
            items[2].textContent = pool["相关领域"] || '-';
            items[3].textContent = pool["跨单元"] || '-';
        }
    }

    // 加载默认数据
    updateUIWithDefault() {
        // 关键指标
        this.updateStatsCard(this.defualtData[0].split('\n').map(l => l.trim()).filter(l => l));
        // 婚育分布
        const deptRows = this.defualtData[1].split('\n').map(l => l.trim()).filter(l => l);
        this.updateMarriageCharts(deptRows);
        // 趋势
        const monthRows = this.defualtData[2].split('\n').map(l => l.trim()).filter(l => l);
        this.updateTrendChart(monthRows);
        // 预产期
        const birthRows = this.defualtData[3].split('\n').map(l => l.trim()).filter(l => l);
        this.updateGanttChart(birthRows);
        // 案源分配
        const caseRows = this.defualtData[4].split('\n').map(l => l.trim()).filter(l => l);
        this.updateCasePool(caseRows);
    }
}

// 创建全局实例
window.guanliManager = new GuanliManager();